package com.harmay.center.monitor.task;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import com.harmay.center.monitor.service.MonitorSubjectService;
import com.harmay.center.monitor.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * @author Zuper
 * @version 1.0
 * @date 2022/11/24 14:13
 */
@Component
@Slf4j
public class RateLimiterTask implements InitializingBean {

    public static Timer timer = new Timer();

    public static volatile Map<String, RateLimiter> limitMap = Maps.newConcurrentMap();

    public static final String SUBJECT_NAME = "subject_name";

    private ObjectMapper jackson = JsonUtils.jackson();

    @Autowired
    private MonitorSubjectService monitorSubjectService;

    /**
     *
     * @author Zuper
     * @date 2022/11/24 15:17
     * @Describe attention plase!!!!这种方法只支持数据库新增subject，如果数据库删除，老的记录还在，需重启当前服务
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                List<Map<String, String>> list = monitorSubjectService.subjectList();
                if (CollectionUtils.isNotEmpty(list)) {
                    list.forEach(map -> {
                        String subject = map.get(SUBJECT_NAME);
                        if (!limitMap.containsKey(subject)) {
                            limitMap.put(subject, RateLimiter.create(0.3, 1, TimeUnit.SECONDS));
                        }
                    });
                }
            }
        }, 1000, 5000);
    }
}
